<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Dispatcher
 * This class provides method to proceed a request to corresponding controller and action
 *
 * @author zelic
 */
class Dispatcher {

    public static function dispatch(&$request, &$response) {
        /**
         * Check if controller and action is valid.
         * If not, dispatch to default controller and 
         * default action with no params
         */
        if (is_a($request, "Request") && is_a($response, "Response")) {
            $controllerClassName = "";
            Loader::loadClass("Controller");
            if (Config::getConfig("system", "module") == "1") {
                $controllerClassName = ((Loader::existClassModule($request->module, $request->controller . "Controller")) ? $request->controller : $request->defaultController) . "Controller";
                Loader::loadClassModule($request->module,$controllerClassName);
            } else {
                $controllerClassName = ((Loader::existClass($request->controller . "Controller")) ? $request->controller : $request->defaultController) . "Controller";
                Loader::loadClass($controllerClassName);
            }

            $controller = new $controllerClassName($request, $response);
            if (is_a($controller, "Controller")) {
                $classMethods = get_class_methods($controllerClassName);
                $action = (array_search($request->action, $classMethods)) ? $request->action : $request->defaultAction;
                $response = $controller->dispatch($action);
            }
        }
    }

}

?>
